# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html

# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
from scrapy.exceptions import DropItem
import pymongo
from scrapy.utils import log
class ShPipeline:

    def open_spider(self,spider):
        self.client = pymongo.MongoClient()
        self.db = self.client.yy

    def process_item(self, item, spider):
        data = dict(item)
        if isinstance(data,dict):
            self.db['lili'].insert_one(data)
            return item
        else:
            raise DropItem('数据格式错误%s' % item)
from . import items
import pymysql
class XMPipeline:
    def open_spider(self, spider):
        data_config = spider.settings['DATA_CONFIG']
        self.conn = pymysql.connect(**data_config['config'])
        self.cursor = self.conn.cursor()

    def close_spider(self,spider):
        self.cursor.close()
        self.conn.close()

    def process_item(self, item, spider):
        if isinstance(item,items.ShItem1):
            try:
                sql = 'insert into lili (title,times) values (%s,%s)'
                self.cursor.execute(sql,(
                    item['title'],
                    item['times'],
                ))
                self.conn.commit()
            except Exception as e:
                self.conn.rollback()
                log.logger.error(e)


class HyPipeline:

    def __init__(self):
        self._set = set()
        self._list = list()

    def process_item(self, item, spider):
        name = item['nick']
        if name in self._set:
            raise DropItem('%s'%item)
        self._set.add(name)
        # self._list.append(name)
        print(len(self._set))
        # print(len(self._list))
        return item


